package com.runvp.common.util.auth;

import com.runvp.common.exception.base.BaseException;
import com.runvp.common.model.auth.BizUserBO;

public class RequestHeaderContext {


    private static final ThreadLocal<RequestHeaderContext> REQUEST_HEADER_CONTEXT_THREAD_LOCAL = new ThreadLocal<>();
    private Long userId;
    private BizUserBO userBO;

    public Long getUserId() {
        return userId;
    }

    public BizUserBO getUserBO() {
        return userBO;
    }


    /**
     * 获取用户ID
     */
    public static Long userId() {
        if (null == getInstance()) {
            return 0L;
        }
        return getInstance().getUserId();
    }

    /**
     * 获取用户信息
     */
    public static BizUserBO getUserInfo() {
        try {
            if (null == getInstance()) {
                throw new BaseException("未登录");
            }
            BizUserBO userInfo = getInstance().getUserBO();
            return userInfo;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("未登录");
        }

    }

    /**
     * 获取用户类型
     */
    public static String getUserType() {
        if (null == getInstance()) {
            return "";
        }
        return getBizUserBO().getType();
    }

    /**
     * 获取用户来源
     */
    public static String getUserSource() {
        return getBizUserBO().getSource();
    }


    public static RequestHeaderContext getInstance() {
        return REQUEST_HEADER_CONTEXT_THREAD_LOCAL.get();
    }
    public static BizUserBO getBizUserBO() {
        BizUserBO userBO = REQUEST_HEADER_CONTEXT_THREAD_LOCAL.get().getUserBO();
        if (null == userBO) {
            throw new BaseException("未登录");
        }
        return userBO;
    }

    public void setContext(RequestHeaderContext context) {
        REQUEST_HEADER_CONTEXT_THREAD_LOCAL.set(context);
    }

    public static void clean() {
        REQUEST_HEADER_CONTEXT_THREAD_LOCAL.remove();
    }

    private RequestHeaderContext(RequestHeaderContextBuild requestHeaderContextBuild) {
        this.userId = requestHeaderContextBuild.userId;
        this.userBO = requestHeaderContextBuild.userBO;
        setContext(this);
    }

    public static class RequestHeaderContextBuild {
        private Long userId;
        private BizUserBO userBO;

        public RequestHeaderContextBuild userId(Long userId) {
            this.userId = userId;
            return this;
        }

        public RequestHeaderContextBuild setUserBO(BizUserBO userBO) {
            this.userBO = userBO;
            return this;
        }

        public RequestHeaderContext build() {
            return new RequestHeaderContext(this);
        }
    }
}
